<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>websocket</title>
</head>

<body>
  <textarea name="" id="message" cols="30" rows="10"></textarea>
  <button id="send">send</button>
  <button id="close">close</button>
  <ul></ul>
  <span>ws</span>
  <script type="text/javascript">
    window.onload = function () {
      var ws = new WebSocket("ws://127.0.0.1:8088");
      var oText = document.getElementById('message');
      var oSend = document.getElementById('send');
      var oClose = document.getElementById('close');
      var oUl = document.getElementsByTagName('ul')[0];
      ws.onopen = function () {
        oSend.onclick = function () {
          if (!/^\s*$/.test(oText.value)) {
            ws.send(oText.value);
          }
        };

      };
      ws.onmessage = function (msg) {
        var str = "<li>" + msg.data + "</li>";
        oUl.innerHTML += str;
        oText.value = ''
      };
      oClose.addEventListener("click", function () {
        console.log('close');
        ws.onclose = function (e) {
          console.log("已断开与服务器的连接");
          ws.close();
        }
        ws.close();
      })
    }
  </script>
</body>

</html>
